import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as deviceApi from '../apis/device'

// 设备状态映射
const deviceStatusMap = {
  false: { label: '故障', type: 'danger' },
  true: { label: '正常', type: 'success' },
}

// 设备类型选项
const deviceTypeOptions = [
  { label: '基站', value: '基站' },
  { label: '路由器', value: '路由器' },
  { label: '交换机', value: '交换机' },
  { label: '中继器', value: '中继器' },
  { label: '网关', value: '网关' }
]

export const useDevice = () => {
  // 设备列表相关状态
  const deviceList = ref([])
  const loading = ref(false)
  const total = ref(0)
  const queryParams = reactive({
    page: 1,
    size: 10,
    deviceName: '',
    deviceType: '',
    status: ''
  })

  // 设备表单相关状态
  const deviceForm = reactive({
    id: '',
    deviceName: '',
    deviceType: '',
    location: '',
    status: 1
  })
  const formVisible = ref(false)
  const formLoading = ref(false)

  // 获取设备列表
  const fetchDeviceList = async () => {
    loading.value = true
    try {
      const response = await deviceApi.getDeviceList(queryParams)
      deviceList.value = response.data.records || []
      total.value = response.data.total || 0
    } catch (error) {
      console.error('获取设备列表失败:', error)
      ElMessage.error('获取设备列表失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索设备
  const handleSearch = () => {
    queryParams.page = 1
    fetchDeviceList()
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(queryParams, {
      page: 1,
      size: 10,
      deviceName: '',
      deviceType: '',
      status: ''
    })
    fetchDeviceList()
  }

  // 打开添加设备对话框
  const handleAdd = () => {
    Object.assign(deviceForm, {
      id: '',
      deviceName: '',
      deviceType: '',
      location: '',
      status: 1
    })
    formVisible.value = true
  }

  // 打开编辑设备对话框
  const handleEdit = async (row) => {
    try {
      const response = await deviceApi.getDeviceDetail(row.id)
      Object.assign(deviceForm, response.data)
      formVisible.value = true
    } catch (error) {
      console.error('获取设备详情失败:', error)
      ElMessage.error('获取设备详情失败')
    }
  }

  // 提交设备表单
  const handleSubmit = async () => {
    formLoading.value = true
    try {
      if (deviceForm.id) {
        await deviceApi.updateDevice(deviceForm)
        ElMessage.success('更新设备成功')
      } else {
        await deviceApi.addDevice(deviceForm)
        ElMessage.success('添加设备成功')
      }
      formVisible.value = false
      fetchDeviceList()
    } catch (error) {
      console.error('保存设备失败:', error)
      ElMessage.error('保存设备失败')
    } finally {
      formLoading.value = false
    }
  }

  // 删除设备
  const handleDelete = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除该设备吗？', '提示', {
        type: 'warning'
      })
      await deviceApi.deleteDevice(id)
      ElMessage.success('删除设备成功')
      fetchDeviceList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除设备失败:', error)
        ElMessage.error('删除设备失败')
      }
    }
  }

  // 批量删除设备
  const handleBatchDelete = async (selectedRows) => {
    if (selectedRows.length === 0) {
      ElMessage.warning('请选择要删除的设备')
      return
    }
    
    try {
      await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.length} 个设备吗？`, '提示', {
        type: 'warning'
      })
      const ids = selectedRows.map(row => row.id)
      await deviceApi.batchDeleteDevices(ids)
      ElMessage.success('批量删除设备成功')
      fetchDeviceList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('批量删除设备失败:', error)
        ElMessage.error('批量删除设备失败')
      }
    }
  }

  // 获取设备状态显示
  const getStatusDisplay = (status) => {
    return deviceStatusMap[status] || { label: '未知', type: 'info' }
  }

  return {
    // 状态
    deviceList,
    loading,
    total,
    queryParams,
    deviceForm,
    formVisible,
    formLoading,
    
    // 常量
    deviceStatusMap,
    deviceTypeOptions,
    
    // 方法
    fetchDeviceList,
    handleSearch,
    handleReset,
    handleAdd,
    handleEdit,
    handleSubmit,
    handleDelete,
    handleBatchDelete,
    getStatusDisplay
  }
}